package xcmg.device.service.company;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.service.basic.CommonGenService;
import xcmg.device.service.param.CompanyDealerParam;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.GeoUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代理商经纬度查询接口
 */
@Service
public class CompanyDealerLatLngService {

    @Autowired
    private CompanyUtil companyUtil;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private CommonGenService commonGenService;


    public List<CompanyDealerVO> queryListByLatLong(CompanyDealerVO vo) {
        List<CompanyDealerDO> doList = companyDealerMapper.querySimpleListByVo(vo);
        List<CompanyDealerVO> voList = collectByDistance(doList, vo.getLatstr(), vo.getLongstr(), vo.getDistance());
        return voList;
    }

    private List<CompanyDealerVO> collectByDistance(List<CompanyDealerDO> doList, String latstr, String longStr, Double distance) {
        if (CollectionUtils.isEmpty(doList)) {
            return Collections.emptyList();
        }
        List<CompanyDealerVO> r = new ArrayList<>(doList.size());
        for (CompanyDealerDO ddo : doList) {
            double dis = GeoUtil.getDistance(latstr, longStr, ddo.getZb());
            CompanyDealerVO vo = BeanUtil.do2bo(ddo, CompanyDealerVO.class);
            vo.setDistance(dis);
            if (null == distance || (dis <= distance * 1000)) {
                r.add(vo);
            }
        }
        if (CollectionUtils.isEmpty(r)) {
            return r;
        }
        List<CompanyDealerVO> rr = r.stream().sorted(Comparator.comparing(CompanyDealerVO::getDistance)).collect(Collectors.toList());
        return rr;
    }

    public List<CompanyDealerVO> queryNearFwzListByLatLong(CompanyDealerParam param) {
        CompanyDealerVO vo = BeanUtil.do2bo(param, CompanyDealerVO.class);
        vo.setOrgId(companyUtil.ynOrgId());
        List<CompanyDealerVO> list = queryListByLatLong(vo);
        if (CollectionUtils.isNotEmpty(list) && list.size() > param.getLimit()) {
            return list.subList(0, param.getLimit());
        }
        return list;
    }
}
